<template>
    <div class="color-picker">
      <!-- 颜色显示区域 -->
      <div class="color-preview" :style="previewStyle"></div>
      
      <!-- 色相选择条 -->
      <div 
        class="hue-bar"
        @mousedown="startHueDrag"
        @touchstart="startHueDrag"
        ref="hueBar"
      >
        <div class="hue-slider" :style="hueSliderStyle"></div>
      </div>
  
      <!-- 饱和度-明度选择区域 -->
      <div 
        class="sv-panel"
        :style="svBackground"
        @mousedown="startSVDrag"
        @touchstart="startSVDrag"
        ref="svPanel"
      >
        <div class="sv-cursor" :style="svCursorStyle"></div>
      </div>
  
      <!-- 颜色值输入 -->
      <div class="color-input">
        <div>{{ hexValue }}</div>
        <div class="btn" @click="getColor">确认</div>
        <!-- <input 
          type="text" 
          v-model="hexValue"
          @input="handleHexInput"
          placeholder="#RRGGBB"
        > -->
      </div>
    </div>
  </template>
  
  <script>
  export default {
    name: 'ColorPicker',
    data() {
      return {
        // 使用HSV颜色模型（Hue, Saturation, Value）
        hue: 0,        // 色相 0-360
        saturation: 1, // 饱和度 0-1
        value: 1,      // 明度 0-1
        isDragging: false, // 拖拽状态
        dragType: null    // 当前拖拽类型（hue/sv）
      }
    },
    computed: {
      // 当前RGB颜色值
      currentRGB() {
        return this.hsvToRgb(this.hue, this.saturation, this.value)
      },
      // 预览区域样式
      previewStyle() {
        return {
          backgroundColor: `rgb(${this.currentRGB.join(',')})`
        }
      },
      // 色相滑块位置
      hueSliderStyle() {
        return {
          left: `${(this.hue / 360) * 100}%`
        }
      },
      // 饱和度-明度区域背景色（当前色相）
      svBackground() {
        const [r, g, b] = this.hsvToRgb(this.hue, 1, 1)
        return {
          backgroundColor: `rgb(${r},${g},${b})`
        }
      },
      // 饱和度明度选择光标位置
      svCursorStyle() {
        return {
          left: `${this.saturation * 100}%`,
          top: `${(1 - this.value) * 100}%`
        }
      },
      // HEX颜色值（双向绑定）
      hexValue: {
        get() {
          return this.rgbToHex(...this.currentRGB)
        },
        set(value) {
            this.value = value
          // 通过输入事件处理
        }
      }
    },
    methods: {
      // 确认颜色
      getColor(){
        this.$emit('getColor',this.hexValue)
      },
      // 将HSV转换为RGB
      hsvToRgb(h, s, v) {
        let r, g, b
        const i = Math.floor(h / 60)
        const f = h / 60 - i
        const p = v * (1 - s)
        const q = v * (1 - f * s)
        const t = v * (1 - (1 - f) * s)
        
        switch (i % 6) {
          case 0: r = v, g = t, b = p; break
          case 1: r = q, g = v, b = p; break
          case 2: r = p, g = v, b = t; break
          case 3: r = p, g = q, b = v; break
          case 4: r = t, g = p, b = v; break
          case 5: r = v, g = p, b = q; break
        }
        
        return [
          Math.round(r * 255),
          Math.round(g * 255),
          Math.round(b * 255)
        ]
      },
  
      // 将RGB转换为HEX
      rgbToHex(r, g, b) {
        return '#' + [r, g, b]
          .map(x => x.toString(16).padStart(2, '0'))
          .join('')
      },
  
      // 处理色相条拖拽开始
      startHueDrag(e) {
        this.dragType = 'hue'
        this.handleDrag(e)
        document.addEventListener('mousemove', this.handleDrag)
        document.addEventListener('mouseup', this.stopDrag)
        document.addEventListener('touchmove', this.handleDrag)
        document.addEventListener('touchend', this.stopDrag)
      },
  
      // 处理饱和度/明度拖拽开始
      startSVDrag(e) {
        this.dragType = 'sv'
        this.handleDrag(e)
        document.addEventListener('mousemove', this.handleDrag)
        document.addEventListener('mouseup', this.stopDrag)
        document.addEventListener('touchmove', this.handleDrag)
        document.addEventListener('touchend', this.stopDrag)
      },
  
      // 处理拖拽事件
      handleDrag(e) {
        if (!this.dragType) return
        
        // const rect = this.$el.getBoundingClientRect()
        let x, y
        
        if (e.type.startsWith('touch')) {
          x = e.touches[0].clientX
          y = e.touches[0].clientY
        } else {
          x = e.clientX
          y = e.clientY
        }
        const hueRect = this.$refs.hueBar.getBoundingClientRect()
        const svRect = this.$refs.svPanel.getBoundingClientRect()
        if (this.dragType === 'hue') {
          const hueWidth = hueRect.width
          const offsetX = x - hueRect.left
          this.hue = Math.max(0, Math.min(360, (offsetX / hueWidth) * 360))
        } else if (this.dragType === 'sv') {
          const svWidth = svRect.width
          const svHeight = svRect.height // 假设SV区域高度200px
          const offsetX = x - svRect.left
          const offsetY = y - svRect.top
          
          this.saturation = Math.max(0, Math.min(1, offsetX / svWidth))
          this.value = Math.max(0, Math.min(1, 1 - (offsetY / svHeight)))
        }
      },
  
      // 停止拖拽
      stopDrag() {
        this.dragType = null
        document.removeEventListener('mousemove', this.handleDrag)
        document.removeEventListener('mouseup', this.stopDrag)
        document.removeEventListener('touchmove', this.handleDrag)
        document.removeEventListener('touchend', this.stopDrag)
      },
  
      // 处理HEX输入
      handleHexInput(e) {
        const hex = e.target.value.replace(/[^0-9a-f]/gi, '')
        if (hex.length === 3 || hex.length === 6) {
          const rgb = this.hexToRgb(hex)
          if (rgb) {
            // 将RGB转换为HSV并更新
            const hsv = this.rgbToHsv(...rgb)
            this.hue = hsv[0]
            this.saturation = hsv[1]
            this.value = hsv[2]
          }
        }
      },
  
      // 将HEX转换为RGB
      hexToRgb(hex) {
        hex = hex.replace(/^#/, '')
        if (hex.length === 3) {
          hex = hex.split('').map(c => c + c).join('')
        }
        if (hex.length !== 6) return null
        
        const num = parseInt(hex, 16)
        return [
          (num >> 16) & 255,
          (num >> 8) & 255,
          num & 255
        ]
      },
  
      // 将RGB转换为HSV
      rgbToHsv(r, g, b) {
        r /= 255, g /= 255, b /= 255
        const max = Math.max(r, g, b)
        const min = Math.min(r, g, b)
        let h, s, v = max
        const d = max - min
        
        s = max === 0 ? 0 : d / max
        
        if (max === min) {
          h = 0
        } else {
          switch (max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break
            case g: h = (b - r) / d + 2; break
            case b: h = (r - g) / d + 4; break
          }
          h *= 60
        }
        
        return [h, s, v]
      }
    }
  }
  </script>
  
  <style scoped lang="scss">
  .color-picker {
    width: 200px;
    height: 200px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  }
  
  .color-preview {
    width: 100%;
    height: 25px;
    border-radius: 4px;
    margin-bottom: 8px;
    border: 1px solid #ddd;
  }
  
  .hue-bar {
    height: 15px;
    background: linear-gradient(to right, 
      #ff0000 0%, #ffff00 17%, 
      #00ff00 33%, #00ffff 50%, 
      #0000ff 67%, #ff00ff 83%, 
      #ff0000 100%);
    border-radius: 10px;
    position: relative;
    margin-bottom: 7px;
  }
  
  .hue-slider {
    width: 12px;
    height: 12px;
    background: #fff;
    border: 2px solid #666;
    border-radius: 50%;
    position: absolute;
    top: 0px;
    transform: translateX(-50%);
  }
  
  .sv-panel {
    width: 100%;
    height: 110px;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 15px;
  }
  
  .sv-panel::before,
  .sv-panel::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  
  .sv-panel::before {
    background: linear-gradient(to right, white 0%, rgba(255,255,255,0) 100%);
  }
  
  .sv-panel::after {
    background: linear-gradient(to top, black 0%, rgba(0,0,0,0) 100%);
  }
  
  .sv-cursor {
    width: 7px;
    height: 7px;
    border: 2px solid #fff;
    border-radius: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  }
  
  .color-input  {
    width: 100%;
    padding-left:10px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-align: center;
    font-family: monospace;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn{
      box-sizing: border-box;
      background: #42b983;
      color: #fff;
      padding: 8px 8px;
      border-radius: 4px;
      font-size: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
      &:hover{
        background: #349876;
      }
    }
  }
  </style>